package ua.org.nuos.sdms.clientgui.client.components;

import com.vaadin.data.Validator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.themes.ChameleonTheme;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.ErrorMessageEvent;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.clientgui.server.exceptions.PasswordValidationException;
import ua.org.nuos.sdms.clientgui.server.validators.PasswordValidator;
import ua.org.nuos.sdms.clientgui.server.validators.PasswordsValidator;

import java.util.Collection;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 14.11.11
 * Time: 20:29
 * To change this template use File | Settings | File Templates.
 */
public class PasswordForm extends Form {

    protected final String PASSWORD_ID = "password";
    protected final int MIN = 8, MAX = 255;

    protected PasswordField passwordField, passwordFieldConfirm;

    @Override
    public void setVisibleItemProperties(Collection<?> visibleProperties) {
        super.getLayout().removeAllComponents();
        super.setVisibleItemProperties(visibleProperties);
    }

    @Override
    protected void attachField(Object propertyId, Field field) {
        if (field == null || propertyId == null) return;
        if (propertyId.equals(PASSWORD_ID)) {
            attachPassword();
        } else {
            super.attachField(propertyId, field);
        }
    }

    protected void attachPassword() {
        passwordField = createPasswordField("Пароль");
        passwordFieldConfirm = createPasswordField("Подтверждение пароля");

        super.getLayout().addComponent(passwordField);
        super.getLayout().addComponent(passwordFieldConfirm);
    }

    protected PasswordField createPasswordField(String caption) {
        PasswordField pf = new PasswordField();
        pf.setStyleName(ChameleonTheme.TEXTFIELD_BIG);
        pf.setWidth("100%");
        pf.setImmediate(true);
        pf.setCaption(caption);
        pf.setRequired(true);
        pf.setRequiredError("Поле \"" + caption + "\" является обязательным.");
        pf.addValidator(
                new StringLengthValidator(
                        "Поле \"" + caption + "\" должно содержать от " + MIN + " до " + MAX + " символов",
                        MIN, MAX, false));
        pf.addValidator(new PasswordValidator("Поле  \"" + caption + "\" содержит некорректные символы"));
        return pf;
    }

    @Override
    public void commit() {
        removeItemProperty(PASSWORD_ID);
        try {
            super.commit();
            String password = getPassword();
            getItemDataSource().getItemProperty(PASSWORD_ID).setValue(password);
        } catch (Validator.InvalidValueException e) {
            passwordField.setValue("");
            passwordFieldConfirm.setValue("");
            throw e;
        } catch (PasswordValidationException e) {
            passwordField.setValue("");
            passwordFieldConfirm.setValue("");
            AppProxy.getInstance().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(e.getMessage()));
            throw new Validator.InvalidValueException(e.getMessage());
        }
    }

    protected String getPassword() {
        String password1 = (String) passwordField.getValue();
        String password2 = (String) passwordFieldConfirm.getValue();
        try {
            passwordField.validate();
            passwordFieldConfirm.validate();
            PasswordsValidator.validate(password1, password2);
        } catch (Validator.InvalidValueException e) {
            throw new PasswordValidationException(e.getMessage(), e);
        }
        return password1;
    }

    @Override
    public void discard() {
        super.discard();
        passwordField.setValue("");
        passwordFieldConfirm.setValue("");
    }

}
